<!-- src/components/ResourceManagement.vue -->
<template>
  <div class="resource-management">
    <!-- 顶部控制区域 -->
    <div class="page-header">
      <div class="header-actions">
        <div class="search-filter">
          <input
            v-model="searchForm.name"
            @input="debounceFetch"
            placeholder="按资源名称搜索"
            class="search-input"
          />
          <input
            v-model="searchForm.code"
            @input="debounceFetch"
            placeholder="按资源编码搜索"
            class="search-input"
          />
          <select v-model="searchForm.category_id" @change="fetchResources" class="filter-select" title="分类筛选">
            <option value="">全部分类</option>
            <option v-for="category in categoryOptions" :key="category.id" :value="category.id">
              {{ category.name }}
            </option>
          </select>
        </div>
        <button class="btn btn-primary" @click="openCreateModal">
          <i class="icon-plus"></i>新增资源
        </button>
      </div>
    </div>

    <!-- 统计卡片 -->
    <div class="stats-cards" v-if="total > 0">
      <div class="stat-card">
        <div class="stat-icon" style="background:#4F46E5"><i class="icon-book"></i></div>
        <div class="stat-content">
          <div class="stat-number">{{ total }}</div>
          <div class="stat-label">资源总数</div>
        </div>
      </div>
      <div class="stat-card">
        <div class="stat-icon" style="background:#10B981"><i class="icon-download"></i></div>
        <div class="stat-content">
          <div class="stat-number">{{ totalDownloads }}</div>
          <div class="stat-label">总下载次数</div>
        </div>
      </div>
    </div>

    <!-- 资源表格 -->
    <div class="table-container" v-if="resources.length > 0">
      <div class="table-header">
        <h3>资源列表</h3>
        <div class="table-actions">
          <button @click="exportResources" class="btn btn-outline">
            <i class="icon-download"></i>导出
          </button>
        </div>
      </div>

      <div class="table-wrapper">
        <table class="data-table">
          <thead>
            <tr>
              <th>ID</th>
              <th>资源名称</th>
              <th>资源编码</th>
              <!-- <th>文件格式</th> -->
              <!-- <th>文件大小</th> -->
              <th>分类</th>
              <th>上传人</th>
              <th>关联课程</th>
              <th>下载次数</th>
              <th>到期时间</th>
              <th>操作</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="resource in resources" :key="resource.id">
              <td>{{ resource.id }}</td>
              <td>{{ resource.name }}.{{ resource.file_format }}</td>
              <td>{{ resource.code }}</td>
              <!-- <td>{{ resource.file_format }}</td>
              <td>{{ resource.file_size }}</td> -->
              <td>{{ resource.category ? resource.category.name : '-' }}</td>
              <td>{{ resource.teacher_name || '-' }}</td>
              <td>{{ resource.course_name || '-' }}</td>
              <td>{{ resource.download_count }}</td>
              <td>{{ formatDate(resource.expiry_date) }}</td>
              <td>
                <div class="action-buttons">
                  <button @click="downloadResource(resource)" class="btn-icon" title="下载">
                    <i class="icon-download"></i>下载
                  </button>
                  <button @click="editResource(resource)" class="btn-icon" title="编辑">
                    <i class="icon-edit"></i>编辑
                  </button>
                  <button @click="confirmDelete(resource.id)" class="btn-icon danger" title="删除">
                    <i class="icon-trash"></i>删除
                  </button>
                </div>
              </td>
            </tr>
          </tbody>
        </table>
      </div>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <div class="pagination-info">共 {{ total }} 条记录，第 {{ currentPage }}/{{ totalPages }} 页</div>
        <div class="pagination">
          <button @click="changePage(currentPage - 1)" :disabled="currentPage === 1" class="pagination-btn">上一页</button>
          <button
            v-for="p in visiblePages"
            :key="p"
            @click="changePage(p)"
            :class="['pagination-btn', { active: p === currentPage }]"
          >
            {{ p }}
          </button>
          <button @click="changePage(currentPage + 1)" :disabled="currentPage === totalPages" class="pagination-btn">下一页</button>
        </div>
      </div>
    </div>

    <!-- 空态 -->
    <div v-else class="empty-state">
      <p>暂无资源数据，点击"新增资源"添加记录。</p>
    </div>

    <!-- 新增/编辑资源模态框 -->
    <div v-if="showModal" class="modal-overlay" @click="closeModal">
      <div class="modal" @click.stop>
        <div class="modal-header">
          <h3>{{ isEdit ? '编辑资源' : '新增资源' }}</h3>
          <button class="modal-close" @click="closeModal"><i class="icon-x"></i></button>
        </div>

        <div class="modal-body">
          <form @submit.prevent="saveResource">
            <div class="form-grid">
              <div class="form-group">
                <label>资源名称 *</label>
                <input v-model="form.name" type="text" required placeholder="请输入资源名称" />
              </div>

              <div class="form-group">
                <label>资源编码 *</label>
                <input v-model="form.code" type="text" required placeholder="请输入资源编码" />
              </div>

              <div class="form-group">
                <label>文件上传 *</label>
                <div class="file-upload-container">
                  <input
                    type="file"
                    ref="fileInput"
                    @change="handleFileUpload"
                    class="file-input"
                    :required="!isEdit"
                  />
                  <div class="file-info" v-if="selectedFile">
                    <span class="file-name">{{ selectedFile.name }}</span>
                    <span class="file-size">({{ formatFileSize(selectedFile.size) }})</span>
                    <button type="button" @click="removeFile" class="file-remove">
                      <i class="icon-x"></i>
                    </button>
                  </div>
                  <div class="file-placeholder" v-else>
                    <i class="icon-upload"></i>
                    <span>点击选择文件或拖拽文件到这里</span>
                  </div>
                </div>
                <div v-if="uploadProgress > 0" class="upload-progress">
                  <div class="progress-bar">
                    <div class="progress-fill" :style="{ width: uploadProgress + '%' }"></div>
                  </div>
                  <span class="progress-text">{{ uploadProgress }}%</span>
                </div>
              </div>

              <div class="form-group">
                <label>文件格式 *</label>
                <input v-model="form.file_format" type="text" required placeholder="如: PDF, MP4, DOCX" />
              </div>

              <div class="form-group">
                <label>文件大小 *</label>
                <input v-model="form.file_size" type="text" required placeholder="如: 2.5MB, 1.2GB" />
              </div>

              <div class="form-group">
                <label>分类 *</label>
                <select v-model="form.category_id" required>
                  <option value="">请选择分类</option>
                  <option v-for="category in categoryOptions" :key="category.id" :value="category.id">
                    {{ category.name }}
                  </option>
                </select>
              </div>

              <div class="form-group">
                <label>授课教师</label>
                <select v-model="form.teacher_id">
                  <option value="">请选择教师</option>
                  <option v-for="teacher in teachers" :key="teacher.id" :value="teacher.id">
                    {{ teacher.name }}
                  </option>
                </select>
              </div>

              <div class="form-group">
                <label>关联课程</label>
                <select v-model="form.course_id">
                  <option value="">请选择课程</option>
                  <option v-for="course in courses" :key="course.id" :value="course.id">
                    {{ course.title }}
                  </option>
                </select>
              </div>

              <div class="form-group">
                <label>到期时间</label>
                <input v-model="form.expiry_date" type="date" />
              </div>
            </div>

            <div class="modal-footer">
              <button type="button" class="btn btn-secondary" @click="closeModal">取消</button>
              <button type="submit" class="btn btn-primary" :disabled="saving || uploading">
                {{ saving || uploading ? '处理中...' : '保存' }}
              </button>
            </div>
          </form>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { API } from '@/services/api'

// 状态
const resources = ref([])
const total = ref(0)
const totalDownloads = ref(0)
const currentPage = ref(1)
const pageSize = ref(15)
const categoryOptions = ref([])
const teachers = ref([])
const courses = ref([])
const fileInput = ref(null)
const selectedFile = ref(null)
const uploadProgress = ref(0)
const uploading = ref(false)

const searchForm = reactive({
  name: '',
  code: '',
  category_id: ''
})

const showModal = ref(false)
const isEdit = ref(false)
const currentResourceId = ref(null)

const form = reactive({
  name: '',
  code: '',
  cloud_id: '',
  file_format: '',
  file_size: '',
  category_id: '',
  teacher_id: '',
  course_id: '',
  expiry_date: ''
})

const loading = ref(false)
const saving = ref(false)

const totalPages = computed(() => Math.ceil(total.value / pageSize.value))

const visiblePages = computed(() => {
  const pages = []
  const maxVisible = 5
  const start = Math.max(1, currentPage.value - Math.floor(maxVisible / 2))
  const end = Math.min(totalPages.value, start + maxVisible - 1)
  for (let i = start; i <= end; i++) pages.push(i)
  return pages
})

// 文件上传处理
const handleFileUpload = (event) => {
  const file = event.target.files[0]
  if (file) {
    selectedFile.value = file
    // 自动填充文件格式和大小
    form.file_format = file.name.split('.').pop().toUpperCase()
    form.file_size = formatFileSize(file.size)
  }
}

const removeFile = () => {
  selectedFile.value = null
  form.file_format = ''
  form.file_size = ''
  if (fileInput.value) {
    fileInput.value.value = ''
  }
}

const formatFileSize = (bytes) => {
  if (bytes === 0) return '0 Bytes'
  const k = 1024
  const sizes = ['Bytes', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

// 文件上传到服务器
const uploadFileToCloud = async (file) => {
  uploading.value = true
  uploadProgress.value = 0
  
  try {
    const formData = new FormData()
    formData.append('file', file)
    
    // 模拟上传进度
    const interval = setInterval(() => {
      uploadProgress.value = Math.min(uploadProgress.value + 10, 90)
    }, 100)
    
    const response = await API.resource.uploadFile(formData)
    
    clearInterval(interval)
    uploadProgress.value = 100
    
    // 等待一小段时间让用户看到100%进度
    await new Promise(resolve => setTimeout(resolve, 200))
    
    uploading.value = false
    return response.url
  } catch (error) {
    uploading.value = false
    throw error
  }
}

// 防抖查询
let searchTimer = null
const debounceFetch = () => {
  clearTimeout(searchTimer)
  searchTimer = setTimeout(() => {
    fetchResources()
  }, 300)
}

// API 调用
const fetchResources = async () => {
  loading.value = true
  try {
    const params = {
      skip: (currentPage.value - 1) * pageSize.value,
      limit: pageSize.value,
      name: searchForm.name || undefined,
      code: searchForm.code || undefined,
      category_id: searchForm.category_id || undefined
    }

    // 删除 undefined
    Object.keys(params).forEach(key => {
      if (params[key] === undefined) delete params[key]
      if (params[key] === '') delete params[key]
    })

    const res = await API.resource.getResources(params)
    resources.value = res.items || []
    total.value = res.total || 0

    // 计算总下载次数
    totalDownloads.value = resources.value.reduce((sum, resource) => sum + (resource.download_count || 0), 0)
  } catch (e) {
    console.error('获取资源失败', e)
  } finally {
    loading.value = false
  }
}

const fetchTeachers = async () => {
  try {
    const response = await API.teacher.getTeachers({ limit: 100 })
    teachers.value = response.items || []
  } catch (error) {
    console.error('获取教师列表失败:', error)
  }
}

const fetchCourses = async () => {
  try {
    const response = await API.course.getCourses({ limit: 100 })
    courses.value = response.items || []
  } catch (error) {
    console.error('获取课程列表失败:', error)
  }
}

const fetchCategories = async () => {
  try {
    // 这里需要根据实际情况调用分类API
    // 假设我们有一个获取分类的API
    // categoryOptions.value = await API.dictionary.getCategories()

    // 临时模拟数据
    categoryOptions.value = [
      { id: 146, name: '视频资料' },
      { id: 147, name: '文档资料' },
      { id: 148, name: '图片资料' },
      { id: 149, name: '软件工具' },
      { id: 150, name: '模板资料' }
    ]
  } catch (e) {
    console.error('获取分类失败', e)
  }
}

const changePage = (page) => {
  if (page < 1 || page > totalPages.value) return
  currentPage.value = page
  fetchResources()
}

const openCreateModal = () => {
  Object.assign(form, {
    name: '',
    code: '',
    cloud_id: '',
    file_format: '',
    file_size: '',
    category_id: '',
    teacher_id: '',
    course_id: '',
    expiry_date: ''
  })
  removeFile()
  uploadProgress.value = 0
  showModal.value = true
  isEdit.value = false
  currentResourceId.value = null
}

const editResource = (resource) => {
  Object.assign(form, {
    name: resource.name,
    code: resource.code,
    cloud_id: resource.cloud_id,
    file_format: resource.file_format,
    file_size: resource.file_size,
    category_id: resource.category_id,
    teacher_id: resource.teacher_id,
    course_id: resource.course_id,
    expiry_date: resource.expiry_date ? resource.expiry_date.substring(0, 10) : ''
  })
  selectedFile.value = null
  uploadProgress.value = 0
  currentResourceId.value = resource.id
  showModal.value = true
  isEdit.value = true
}

const saveResource = async () => {
  saving.value = true
  
  try {
    // 如果是新增或者选择了新文件，先上传文件
    if ((!isEdit.value || selectedFile.value) && selectedFile.value) {
      form.cloud_id = await uploadFileToCloud(selectedFile.value)
    }

    const payload = {
      name: form.name,
      code: form.code,
      cloud_id: form.cloud_id,
      file_format: form.file_format,
      file_size: form.file_size,
      category_id: form.category_id,
      teacher_id: form.teacher_id || null,
      course_id: form.course_id || null,
      expiry_date: form.expiry_date || null
    }

    if (isEdit.value && currentResourceId.value) {
      await API.resource.updateResource(currentResourceId.value, payload)
    } else {
      await API.resource.createResource(payload)
    }

    closeModal()
    fetchResources()
  } catch (e) {
    console.error('保存资源失败', e)
    alert('保存失败: ' + (e.response?.data?.detail || e.message))
  } finally {
    saving.value = false
    uploading.value = false
  }
}

const downloadResource = async (resource) => {
  try {
    // 增加下载次数
    await API.resource.incrementDownloadCount(resource.id)

    // 构建正确的文件访问URL
    const baseURL = API.resource.apiClient?.defaults?.baseURL || 'http://localhost:8000';
    
    let fileUrl;
    if (resource.cloud_id.startsWith('/uploads')) {
      // 已经是完整的路径格式，如 /uploads\filename
      // 需要将反斜杠转换为正斜杠
      const cleanPath = resource.cloud_id.replace(/\\/g, '/');
      fileUrl = baseURL + cleanPath;
    } else if (resource.cloud_id.startsWith('cloud_')) {
      // 是cloud_timestamp_filename格式
      // 移除"cloud_"前缀获取实际文件名
      const fileName = resource.cloud_id.replace('cloud_', '');
      fileUrl = `${baseURL}/uploads/${fileName}`;
    } else {
      // 其他情况，直接放在uploads目录下
      fileUrl = `${baseURL}/uploads/${resource.cloud_id}`;
    }

    // 使用axios获取文件内容
    const response = await API.resource.apiClient.get(fileUrl, {
      responseType: 'blob'
    });

    // 创建Blob对象和下载链接
    const blob = new Blob([response], { type: response.type });
    const downloadUrl = window.URL.createObjectURL(blob);
    
    // 创建一个隐藏的a标签来触发下载
    const link = document.createElement('a');
    link.href = downloadUrl;
    // 使用资源名称和格式作为下载文件名
    link.download = resource.name + '.' + resource.file_format;
    link.style.display = 'none';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    
    // 清理创建的对象URL
    window.URL.revokeObjectURL(downloadUrl);

    // 刷新列表以更新下载次数
    fetchResources()
  } catch (e) {
    console.error('下载资源失败', e)
    alert('下载失败: ' + (e.response?.data?.detail || e.message))
  }
}

const confirmDelete = async (id) => {
  if (!confirm('确定要删除该资源吗？')) return
  try {
    await API.resource.deleteResource(id)
    fetchResources()
  } catch (e) {
    console.error('删除资源失败', e)
    alert('删除失败: ' + (e.response?.data?.detail || e.message))
  }
}

const closeModal = () => {
  showModal.value = false
  isEdit.value = false
  currentResourceId.value = null
  Object.assign(form, {
    name: '',
    code: '',
    cloud_id: '',
    file_format: '',
    file_size: '',
    category_id: '',
    teacher_id: '',
    course_id: '',
    expiry_date: ''
  })
  removeFile()
  uploadProgress.value = 0
}

const exportResources = () => {
  // 简单示例：触发后端导出或在前端下载 CSV
  console.log('导出资源数据')
}

const formatDate = (d) => {
  if (!d) return '-'
  const date = new Date(d)
  if (Number.isNaN(date.getTime())) return d
  return date.toLocaleDateString('zh-CN')
}

// 初始加载
onMounted(() => {
  fetchResources()
  fetchCategories()
  fetchTeachers()
  fetchCourses()
})
</script>

<style scoped>
.resource-management {
  padding: 20px;
}
.page-header {
  margin-bottom: 12px;
}
.header-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 12px;
}
.search-filter {
  display: flex;
  gap: 12px;
  align-items: center;
  flex-wrap: wrap;
}
.search-input {
  width: 200px;
  padding: 8px 12px;
  border: 1px solid #D1D5DB;
  border-radius: 6px;
}
.filter-select {
  padding: 8px 12px;
  border-radius: 6px;
  border: 1px solid #D1D5DB;
}
.btn {
  padding: 8px 14px;
  border-radius: 6px;
  border: none;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 6px;
}
.btn-primary {
  background: #4F46E5;
  color: white;
}
.btn-outline {
  background: white;
  border: 1px solid #4F46E5;
  color: #4F46E5;
}
.btn-secondary {
  background: #F3F4F6;
  color: #374151;
}
.stats-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 16px;
  margin: 16px 0 8px;
}
.stat-card {
  background: white;
  padding: 14px;
  border-radius: 8px;
  display: flex; align-items: center; gap: 12px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}
.stat-icon {
  width: 44px; height: 44px; border-radius: 8px;
  display: flex; align-items: center; justify-content: center; color: white;
}
.stat-content .stat-number {
  font-size: 18px; font-weight: 600;
}
.table-container {
  background: white; border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  margin-top: 14px;
}
.table-header {
  padding: 14px 16px; border-bottom: 1px solid #E5E7EB; display: flex; justify-content: space-between; align-items: center;
}
.table-wrapper {
  overflow-x: auto;
}
.data-table {
  width: 100%; border-collapse: collapse;
}
.data-table th, .data-table td {
  padding: 12px; border-bottom: 1px solid #E5E7EB; text-align: left;
}
.data-table th {
  background: #F9FAFB; font-weight: 600;
}
.action-buttons {
  display: flex; gap: 6px;
}
.btn-icon {
  border-radius: 6px;
  border: none;
  background: #F3F4F6;
  color: #6B7280;
  display: inline-flex;
  align-items: center;
  padding: 6px 10px;
  gap: 4px;
  justify-content: flex-start;
  cursor: pointer;
}

.btn-icon:hover {
  background: #E5E7EB;
}

.btn-icon.danger:hover {
  background: #FEE2E2;
  color: #EF4444;
}

.pagination-wrapper {
  padding: 12px 16px; display: flex; justify-content: space-between; align-items: center;
  border-top: 1px solid #E5E7EB;
}
.pagination-btn {
  padding: 6px 10px; border: 1px solid #D1D5DB; border-radius: 6px; background: white;
  cursor: pointer;
  margin: 0 2px;
}
.pagination-btn.active {
  background: #4F46E5; color: white; border-color: #4F46E5;
}
.pagination-btn:disabled {
  opacity: 0.5; cursor: not-allowed;
}
.modal-overlay {
  position: fixed; left:0; top:0; right:0; bottom:0;
  background: rgba(0,0,0,0.5); display: flex; align-items: center; justify-content: center;
  z-index: 1000;
}
.modal {
  background: white; border-radius: 8px; width: 90%; max-width: 800px; max-height: 90vh; overflow: auto;
}
.modal-header {
  padding: 14px 16px; border-bottom: 1px solid #E5E7EB; display: flex; justify-content: space-between; align-items: center;
}
.modal-body { padding: 16px; }
.modal-footer {
  display: flex; justify-content: flex-end; gap: 10px; padding: 12px 16px; border-top: 1px solid #E5E7EB;
}
.form-grid {
  display: grid; grid-template-columns: repeat(auto-fit, minmax(240px, 1fr)); gap: 12px;
}
.form-group { display: flex; flex-direction: column; gap: 6px; }
.form-group label { font-size: 13px; color: #374151; }
.form-group input, .form-group select, .form-group textarea {
  padding: 8px 10px; border: 1px solid #D1D5DB; border-radius: 6px; font-size: 14px;
}
.form-group textarea { resize: vertical; min-height: 80px; }

/* 文件上传样式 */
.file-upload-container {
  position: relative;
  border: 2px dashed #D1D5DB;
  border-radius: 6px;
  padding: 16px;
  text-align: center;
  cursor: pointer;
  transition: border-color 0.3s;
}

.file-upload-container:hover {
  border-color: #4F46E5;
}

.file-input {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  opacity: 0;
  cursor: pointer;
}

.file-info {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
}

.file-name {
  font-weight: 500;
  color: #374151;
}

.file-size {
  color: #6B7280;
  font-size: 12px;
}

.file-remove {
  background: none;
  border: none;
  color: #EF4444;
  cursor: pointer;
  padding: 4px;
}

.file-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
  color: #6B7280;
}

.file-placeholder i {
  font-size: 24px;
}

/* 上传进度条 */
.upload-progress {
  margin-top: 8px;
  display: flex;
  align-items: center;
  gap: 8px;
}

.progress-bar {
  flex: 1;
  height: 6px;
  background: #E5E7EB;
  border-radius: 3px;
  overflow: hidden;
}

.progress-fill {
  height: 100%;
  background: #10B981;
  transition: width 0.3s;
}

.progress-text {
  font-size: 12px;
  color: #6B7280;
  min-width: 40px;
}

.empty-state {
  padding: 40px 0;
  text-align: center;
  color: #6B7280;
}

@media (max-width: 768px) {
  .header-actions {
    flex-direction: column;
    align-items: stretch;
  }

  .search-filter {
    flex-direction: column;
    align-items: stretch;
  }

  .search-input, .filter-select {
    width: 100%;
  }

  .form-grid {
    grid-template-columns: 1fr;
  }

  .data-table {
    font-size: 14px;
  }

  .action-buttons {
    flex-direction: column;
    gap: 4px;
  }

  .file-info {
    flex-direction: column;
    text-align: center;
  }
}
</style>